package divide;

public class MaxSubArray {
    private static final int[] array = {13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7};

    public static void main(String[] args) {
        MaxArrayHelper maxArrayHelper = findMaxSubArray(0, array.length - 1);
        System.out.println("left index:" + maxArrayHelper.maxLeftIndex);
        System.out.println("right index:" + maxArrayHelper.maxRightIndex);
        System.out.println("max sum:" + maxArrayHelper.maxSum);
    }

    private static MaxArrayHelper findMaxSubArray(int low, int high) {
        if (low == high) {
            MaxArrayHelper maxArrayHelper = new MaxArrayHelper();
            maxArrayHelper.maxLeftIndex = low;
            maxArrayHelper.maxRightIndex = high;
            maxArrayHelper.maxSum = array[low];
            return maxArrayHelper;
        } else {
            int mid = Math.floorDiv(low + high, 2);
            MaxArrayHelper leftHelper = findMaxSubArray(low, mid);
            MaxArrayHelper crossHelper = findCrossMaxSubArray(low, mid, high);
            MaxArrayHelper rightHelper = findMaxSubArray(mid + 1, high);

            if (leftHelper.maxSum >= crossHelper.maxSum && leftHelper.maxSum >= rightHelper.maxSum) {
                return leftHelper;
            } else if (rightHelper.maxSum >= crossHelper.maxSum) {
                return rightHelper;
            } else return crossHelper;
        }
    }

    private static MaxArrayHelper findCrossMaxSubArray(int low, int mid, int high) {
        MaxArrayHelper maxArrayHelper = new MaxArrayHelper();
        int leftSun = Integer.MIN_VALUE;
        int sum = 0;
        for (int i = mid; i >= low; i--) {
            sum += array[i];
            if (sum > leftSun) {
                leftSun = sum;
                maxArrayHelper.maxLeftIndex = i;
            }
        }

        int rightSum = Integer.MIN_VALUE;
        sum = 0;
        for (int j = mid + 1; j <= high; j++) {
            sum += array[j];
            if (sum > rightSum) {
                rightSum = sum;
                maxArrayHelper.maxRightIndex = j;
            }
        }

        maxArrayHelper.maxSum = leftSun + rightSum;
        return maxArrayHelper;
    }

    static class MaxArrayHelper {
        int maxLeftIndex;
        int maxRightIndex;
        int maxSum;
    }
}
